package net.mayee.alice.web.controller.admin.validateimg;

import jodd.log.Logger;
import jodd.log.LoggerFactory;
import jodd.props.Props;
import net.mayee.alice.common.Definiens;
import net.mayee.alice.entity.coder.SystemCodeItem;
import net.mayee.alice.web.controller.base.BaseController;
import net.mayee.common.AliceHelper;
import net.mayee.common.CoderHelper;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@RequestMapping(value = "/vi")
@Controller
public class ValidateImgController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ValidateImgController.class);

    /**
     * 生成验证码图片，每刷新10次，会有30秒的CD
     *
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping(value = "/ajax/loadValidateImg", method = RequestMethod.POST)
    public void loadValidateImg(@RequestParam("r") String r, HttpServletResponse response,
                                HttpServletRequest request) throws IOException, JSONException {
        List<String> errorMsgList = new ArrayList<String>();
        HashMap<String, String> reMap = new HashMap<String, String>();
        HttpSession session = request.getSession();
        Props props = AliceHelper.getInstance().getJoddProps();

        if (session.getAttribute(Definiens.SESSIONKEY_VALIDATEIMG_LAST_TIME) != null) {
            long last_time = (Long) session
                    .getAttribute(Definiens.SESSIONKEY_VALIDATEIMG_LAST_TIME);
            // Calendar c = Calendar.getInstance();
            long now = Calendar.getInstance().getTimeInMillis();
            //System.out.println("time:"+(now - last_time));

            long vi_refresh_time = Definiens.DEF_VALIDATEIMG_ACTION_TIME;
            try {
                vi_refresh_time = Long.parseLong(props.getValue("validateimg.refresh.reset.time"));
            } catch (Exception e) {
                LOGGER.error(
                        AliceHelper.getInstance().getApplicationConfigErrorMessage("validateimg.refresh.reset.time", vi_refresh_time), e);
            }
            if (now - last_time > vi_refresh_time) {
                session.setAttribute(Definiens.SESSIONKEY_REFRESH_NUM, new Integer(1));
            }
            session.setAttribute(Definiens.SESSIONKEY_VALIDATEIMG_LAST_TIME, now);
        } else {
            session.setAttribute(Definiens.SESSIONKEY_VALIDATEIMG_LAST_TIME, Calendar
                    .getInstance().getTimeInMillis());
        }

        /* check refresh vi num */
        Integer vi_refresh_num = new Integer(0);
        if (session.getAttribute(Definiens.SESSIONKEY_REFRESH_NUM) != null) {
            vi_refresh_num = (Integer) session
                    .getAttribute(Definiens.SESSIONKEY_REFRESH_NUM);
        }
        session.setAttribute(Definiens.SESSIONKEY_REFRESH_NUM, ++vi_refresh_num);

        /* def max refresh count */
        Integer def_refresh_max_count = new Integer(Definiens.DEF_VALIDATEIMG_MAX_REFRESH_NUM);
        try {
            def_refresh_max_count = Integer.parseInt(props.getValue("validateimg.refresh.max.count"));
        } catch (Exception e) {
            LOGGER.error(
                    AliceHelper.getInstance().getApplicationConfigErrorMessage("validateimg.refresh.max.count", def_refresh_max_count), e);
        }

        if (vi_refresh_num < def_refresh_max_count) {
            String bvp = (String) session
                    .getAttribute(Definiens.SESSIONKEY_LOGIN_VALIDATEIMG_PATH);
            if (bvp == null || (r != null && r.equals("1"))) {
                reMap.put("validateimgPath", AliceHelper.getInstance().buildOrResetValidateImg(request));
            } else {
                reMap.put("validateimgPath", bvp);
            }
        } else {
            SystemCodeItem sci = CoderHelper.getInstance().getObjectBySystemCode(Definiens.ERR_VALIDATEIMG_REFRESH_TOO_MUCH);
            errorMsgList.add(this.getMessage(sci.getText(), sci.getDefText()));
        }

        request.setAttribute("reJSON",
                this.getAjaxValidateJSONString(errorMsgList, reMap));
    }

    @RequestMapping(value = "/ajax/checkValidateImg", method = RequestMethod.POST)
    public void checkValidateImg(@RequestParam("vi_code") String vi_code, HttpServletResponse response,
                                 HttpServletRequest request) throws IOException, JSONException {
        Map<String, String> reMap = new HashMap<String, String>();
        Props props = AliceHelper.getInstance().getJoddProps();
        boolean isValidateCheck = true;
        String system_validateimg_check = props.getValue("system.validateimg.check");
        try {
            isValidateCheck = Boolean.parseBoolean(system_validateimg_check);
        } catch (Exception e) {
            LOGGER.error(
                    AliceHelper.getInstance().getApplicationConfigErrorMessage("system.validateimg.check", system_validateimg_check), e);
        }
        if (!isValidateCheck || (StringUtils.isNotBlank(vi_code) && vi_code.trim().length() == 5
                && AliceHelper.getInstance().checkValidateImg(vi_code, request))) {
            request.setAttribute("reJSON", this.getAjaxValidateJSONString(null));
        } else {
            List<String> errorMsgList = new ArrayList<String>();
            SystemCodeItem sci = CoderHelper.getInstance().getObjectBySystemCode(Definiens.ERR_VALIDATEIMG_CHECK_FAIL);
            errorMsgList.add(this.getMessage(sci.getText(), sci.getDefText()));
            request.setAttribute("reJSON", this.getAjaxValidateJSONString(errorMsgList));
        }

    }

}
